package net.cloudcodex.server.rpc;

import java.util.List;

import net.cloudcodex.server.Context;
import net.cloudcodex.server.DTOUtil;
import net.cloudcodex.server.data.Data;
import net.cloudcodex.server.data.home.CampaignSummary;
import net.cloudcodex.server.data.home.CharacterSummary;
import net.cloudcodex.shared.Errors;
import net.cloudcodex.shared.NotificationType;
import net.cloudcodex.shared.dto.Result;
import net.cloudcodex.shared.dto.home.HomeDTO;
import net.cloudcodex.shared.rpc.HomeRPC;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * The server side implementation of the RPC homeService.
 */
@SuppressWarnings("serial")
public class HomeRPCImpl extends AbstractRPC implements HomeRPC {

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Result<HomeDTO> getHome() {
		
		final Context context = createContext();
		final Data.User user = context.getUser();

		if(user == null || user.getNickname() == null) {
			context.addError(Errors.NOT_REGISTERED);
			return createResult(context, null);
		}
		
		// Build the Home DTO
		final HomeDTO home = new HomeDTO();
		home.setNickname(user.getNickname());
		home.setUserId(user.getKey().getId());
		
		/*
		 * General notifications.
		 */
		home.setNotifications(DTOUtil.mapNotification(
			homeService.getNotifications(context, null), NotificationType.GLOBAL));

		/*
		 * User notifications.
		 */
		home.setUserNotifications(DTOUtil.mapNotification(
			homeService.getNotifications(context, user.getKey()), NotificationType.USER));
		
		/*
		 *	Characters
		 */
		final List<CharacterSummary> characters = homeService.getCharacterSummaries(context);
		home.setCharacters(DTOUtil.mapCharacterSummary(characters));
		
		/*
		 *	Campaigns
		 */
		final List<CampaignSummary> campaigns = homeService.getCampaignSummaries(context);
		home.setCampaigns(DTOUtil.mapCampaignSummary(campaigns));
		
		return createResult(context, home);
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public Result<Boolean> register(String nickname) {
		
		// Try to find the user in datastore
		Data.User user = findCurrentUser();
		
		final UserService userService = UserServiceFactory.getUserService();
		final User guser = userService.getCurrentUser();

		// if not found, create a new one.
		if(user == null) {
			user = new Data.User();
			user.setEmail(guser.getEmail());
		}
		
		if(user.getGoogleId() == null) {
			user.setGoogleId(guser.getUserId());
		}
		
		final Context context = new Context(user);

		user = homeService.register(context, nickname);

		return createResult(context, user != null);
	}
	
}
